#!/usr/local/python/bin/python
# coding=utf-8
__author__ = 'cz'

import json
import urllib2
from tdtools.DcpException import DcpException
from tdtools import Config_tdsql_prd as Config, LogUtil

_logger=LogUtil._logger
class HttpUtil():

    # ajax 数据提交
    @staticmethod
    def httpPost(url, jsonVal):
        global _logger
        try:
            _logger.info('请求路径:%s  请求参数：%s  ' %(url,jsonVal))
            req = HttpUtil.getJsonReq(url, jsonVal)
            response = urllib2.urlopen(req)
            return response.read()
        except Exception as e:
            raise DcpException(Config.EXCEPTION_HTTP_POST,
                               'URL:' + str(url) + ' JSON:' + str(jsonVal) + ' 远端调用异常!' + e.message)

    @staticmethod
    def httpPost2(url, jsonVal):
        try:
            print ('HttpUtil.httpPost2 ')
            print (jsonVal)
            req = HttpUtil.getJsonReq2(url, jsonVal)
            print (req)
            response = urllib2.urlopen(req)
            return response.read()
        except Exception as e:
            print("异常信息：" + e.message)
            raise DcpException(Config.EXCEPTION_HTTP_POST,
                               'URL:' + str(url) + ' JSON:' + str(jsonVal) + ' 远端调用异常!' + e.message)

    @staticmethod
    def getJsonReq(url, jsonVal):
        jdata = json.dumps(jsonVal)
        req = urllib2.Request(url, jdata)
        req.add_header("Content-type", "application/json")
        return req

    @staticmethod
    def getJsonReq2(url, jsonVal):
        jdata = json.dumps(jsonVal)
        req = urllib2.Request(url, jdata)
        req.add_header("Content-type", "application/x-www-form-urlencoded")
        return req

    # url get处理
    @staticmethod
    def httpGet(url):
        try:
            response = urllib2.urlopen(url)
            return response.read()
        except Exception as e:
            print('HTTP GET 远端调用异常!' + e.message)
            raise DcpException(Config.EXCEPTION_HTTP_GET, 'HTTP GET 远端调用异常!' + e.message)
